# Packages
import os
from pandas.core.indexes.base import Index

# Self-defined modules
from utility import *


REPORT_FORM_TYPE = '个人市场'


def _generate_index_dim_and_update_period(columns) -> (str, str):
    '''
    生成指标维度及更新周期
    :param columns: 数据表列的列表
    :return: 指标维度，更新周期
    '''
    index_dim, update_period = '', ''
    if sum(map(lambda x: PROVINCE_LABEL in x, columns)):
        index_dim = PROVINCE_LABEL
    if MONTH_PERIOD_LABEL in columns:
        index_dim = '{}/{}'.format(index_dim, MONTH_PERIOD_LABEL)
        update_period = MONTH
    return index_dim, update_period


def _fill_in_output(file_path: str, output_df_dict: dict):
    '''
    填入信息至产出表
    :param file_path: 待梳理报表路径
    :param output_df_dict: 产出表字典
    '''
    if check_suffix(file_path, FILE_SUFFIXES):
        df_dict = read_form(file_path)
        if df_dict is not None:
            file_name = file_path.split('/')[-1]
            print(PROCESSING_PROMPT.format(file_name))
            for sheet_name, df in df_dict.items():

                if df is not None:
                    if df.columns.__class__ == Index:
                        updated_cols = df.columns
                    else:
                        updated_cols = [reduce(lambda x, y: '{} {} {}'.format(x, index_split, y) if x and y else x + y,
                                               list(map(lambda x: '' if INVALID_COLUMN in x else x, col)))
                                        for col in df.columns]

                    index_dim, update_period = _generate_index_dim_and_update_period(df.columns)

                    for col in updated_cols:
                        output_df_dict[CATEGORY].append(REPORT_FORM_TYPE)
                        output_df_dict[BUSI_TYPE].append('')
                        output_df_dict[FORM_NAME].append(file_name.split('.')[0].split('_')[-1])
                        output_df_dict[INDEX_SPLIT].append(col)
                        output_df_dict[INDEX_NAME].append('')
                        output_df_dict[DETAILED_SUM].append('')
                        output_df_dict[INDEX_DIM].append(index_dim)
                        output_df_dict[UPDATE_PERIOD].append(update_period)

                    print(PROCESSED_PROMPT.format(sheet_name))
                    break


                else:
                    print(NOT_PROCESSED_PROMPT.format(sheet_name))

def traverse_files(folder_path: str) -> [dict]:
    '''
    加载指定文件夹中所有数据表
    :param folder_path: 文件夹路径
    :return: 形如[{页名: 数据框}]的列表
    '''
    output_df_dict = OUTPUT_TEMPLATE

    for root, dirs, files in os.walk(folder_path):
        for file in files:
            file_path = os.path.join(root, file)
            _fill_in_output(file_path, output_df_dict)

    pd.DataFrame(output_df_dict).to_excel(OUTPUT_FILE_REPORT_FORM_SUM, index=False)


if __name__ == '__main__':
    traverse_files(REPORT_FORM_FOLDER)

